package org.jtb.quickr;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

abstract class FlickrRequest {
    private String baseUrl;
    private String apiKey;
    private Map<String,String> args;
    
    public FlickrRequest(String baseUrl, String apiKey) {
        this.setBaseUrl(baseUrl);
        this.setApiKey(apiKey);
        this.args = new HashMap<String,String>();
    }
    
    public abstract FlickrResponse execute() throws QuickrException;
            
    protected String getBaseUrl() {
        return baseUrl;
    }

    private void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    protected String getApiKey() {
        return apiKey;
    }

    private void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }
    
    protected Map<String,String> getArgs() {
        putArg("api_key", getApiKey());
        
        return Collections.unmodifiableMap(args);
    }
    
    protected void putArg(String key, String val) {
        if (key == null) {
            throw new NullPointerException("null key not allowed");
        }
        if (val == null) {
            return;
        }
        args.put(key, val);
    }

    protected static String join(Collection<?> collection, char c) {
        if (collection == null) {
            return null;            
        }
        StringBuffer b = new StringBuffer();
        for (Iterator<?> i = collection.iterator(); i.hasNext(); ) {
            b.append(i.next().toString());
            if (i.hasNext()) {
                b.append(c);
            }
        }
        
        return b.toString();
    }     
    
}
